var $sql = require('./moneyMapping');
var mysql = require('../../config/mysql');// 获取数据库连接配置

var async = require('async');

var config = require('../../config/config');//
var mapping = require('../mapping');//

var dateFormat = require('../../util/dateFormat');//

module.exports = {
    index: function (req, res, next) {
        mysql.db.getConnection(function(connection){
            connection.beginTransaction(function(err) {
                if (err) {
                    console.log(err);
                    return;
                }
                //查询是否有未读信息
                var task1 = function(callback){
                    connection.query($sql.message, [req.session.user.userId,1], function(err, result) {
                        if (err) {
                            console.log(err);
                            callback(err,null);
                            return;
                        }
                        console.log('第一次查询!');
                        callback(null,result);
                    })
                }
                //查询已启用的关系列表
                var task2 = function(callback){
                    connection.query($sql.list, [req.session.user.userId,req.session.user.userId,1], function(err, result) {
                        if (err) {
                            console.log(err);
                            callback(err,null);
                            return;
                        }
                        console.log('第二次查询!');
                        callback(null,result);
                    })
                }
                async.series([task1, task2],function(err,result){
                    if (err) {
                        console.log(err);
                        //回滚
                        connection.rollback(function() {
                            console.log('出现错误,回滚!');
                            //释放资源
                            connection.release();
                            res.json({code:config.code.error,message:err,content:''})
                        });
                        return;
                    }
                    //提交
                    connection.commit(function(err) {
                        if (err) {
                            console.log(err);
                            return;
                        }
                        console.log('成功,提交!');
                        //释放资源
                        connection.release();
                        res.json({code:config.code.success,message:config.message.success,content:result})
                    });
                })
            });
        })

    },

    /* 信息列表 */
    message: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);
        //必填参数是否传值
        if(body.type == undefined){
            res.json({ code: config.code.parameterNull,'message': config.message.parameterNull+'type 1未读 2已读',content:''});
            return;
        }
        var type=body.type || null;
        //必填参数是否为空
        if(type == null){
            res.json({ code: config.code.valNull,'message': config.message.valNull+'type 1未读 2已读',content:''});
            return;
        }
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.messageList, [req.session.user.userId,type], function(err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                res.json({ code: config.code.success,'message': config.message.success,content:result});
            });
        });

    },
    /* 信息确认 */
    isMessage: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);

        //必填参数是否传值
        if(body.id == undefined||body.state == undefined){
            res.json({ code: config.code.parameterNull,'message': config.message.parameterNull+'id state 1启用(通过) 2删除(不通过)',content:''});
            return;
        }
        var id=body.id || null;
        var state=body.state || null;
        var message='';
        if(state==1){
            message='通过';
        }else{
            message='不通过';
        }
        var relationshipId='';
        //必填参数是否为空
        if(id == null||state == null){
            res.json({ code: config.code.valNull,'message': config.message.valNull+'id state 1启用(通过) 2删除(不通过)',content:''});
            return;
        }
        mysql.pool.getConnection(function(err, connection) {
            //
            connection.query($sql.findMessage, [id], function(err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                if(result.length>0&&result[0].type==1){
                    relationshipId=result[0].relationshipId;
                    var userId=result[0].payUserId;
                    mysql.db.getConnection(function(connection){
                        connection.beginTransaction(function(err) {
                            if (err) {
                                console.log(err);
                                return;
                            }
                            //修改信息状态
                            var task1 = function(callback){
                                connection.query($sql.isMessage, [id], function(err, result) {
                                    if (err) {
                                        console.log(err);
                                        callback(err,null);
                                        return;
                                    }
                                    console.log('第一次修改!');
                                    callback(null,result);
                                })
                            }
                            //修改关系信息状态
                            var task2 = function(callback){
                                connection.query($sql.isRelationship, [state,relationshipId], function(err, result) {
                                    if (err) {
                                        console.log(err);
                                        callback(err,null);
                                        return;
                                    }
                                    console.log('第二次修改!');
                                    callback(null,result);
                                })
                            }
                            //增加发起人信息
                            var task3 = function(callback){
                                connection.query($sql.addMessage, [userId,relationshipId,message,1,dateFormat.format('yyyy-MM-dd hh:mm:ss')], function(err, result) {
                                    if (err) {
                                        console.log(err);
                                        callback(err,null);
                                        return;
                                    }
                                    console.log('第二次修改!');
                                    callback(null,result);
                                })
                            }
                            async.series([task1, task2, task3],function(err,result){
                                if (err) {
                                    console.log(err);
                                    //回滚
                                    connection.rollback(function() {
                                        console.log('出现错误,回滚!');
                                        //释放资源
                                        connection.release();
                                        res.json({code:config.code.error,message:err,content:''})
                                    });
                                    return;
                                }
                                //提交
                                connection.commit(function(err) {
                                    if (err) {
                                        console.log(err);
                                        return;
                                    }
                                    console.log('修改成功,提交!');
                                    //释放资源
                                    connection.release();
                                    res.json({code:config.code.success,message:config.message.success,content:result})
                                });
                            })
                        });
                    })
                }else{
                    res.json({code:config.code.valError,message:'信息ID不存在或信息已操作',content:''})
                }
            });
        });
    },
    /* 信息确认提示 */
    okMessage: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);

        //必填参数是否传值
        if(body.id == undefined){
            res.json({ code: config.code.parameterNull,'message': config.message.parameterNull+'id',content:''});
            return;
        }
        var id=body.id || null;
        //必填参数是否为空
        if(id == null){
            res.json({ code: config.code.valNull,'message': config.message.valNull+'id',content:''});
            return;
        }
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.okMessage, [id,req.session.user.userId], function(err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                if(result.affectedRows==0){
                    res.json({ code: config.code.success,'message': '信息ID与用户ID不符',content:result});
                }else if(result.changedRows==0) {
                    res.json({ code: config.code.success,'message': '信息已操作过',content:result});
                }else {
                    res.json({ code: config.code.success,'message': config.message.success,content:result});
                }
            });
        });

    },
    /* 搜索关系人列表 */
    relationshipFind: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);
        var userName=body.userName || '';
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.relationshipFind, ['%'+userName+'%',req.session.user.userName], function(err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                res.json({ code: config.code.success,'message': config.message.success,content:result});
            });
        });

    },
    /* 增加关系人 */
    relationshipAdd: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);
        //必填参数是否传值
        if(body.userId == undefined){
            res.json({ code: config.code.parameterNull,'message': config.message.parameterNull+'userId',content:''});
            return;
        }
        var userId=body.userId || null;
        //必填参数是否为空
        if(userId == null){
            res.json({ code: config.code.valNull,'message': config.message.valNull+'userId',content:''});
            return;
        }
        userId=parseInt(userId);
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.userId, [userId], function(err, result) {
                if (err) {
                    connection.release();
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                if(result.length>0&&req.session.user.userId!=userId){
                    connection.query($sql.relationshipAddFind, [req.session.user.userId,userId], function(err, result) {
                        connection.release();
                        if (err) {
                            console.log(err);
                            res.json({ code: config.code.error,'message': err,content:''});
                            return;
                        }
                        if(result.length==0){
                            mysql.db.getConnection(function(connection){
                                connection.beginTransaction(function(err) {
                                    if (err) {
                                        console.log(err);
                                        res.json({code:config.code.error,message:err,content:''})
                                        return;
                                    }
                                    //增加关系信息
                                    connection.query($sql.relationshipAdd, [req.session.user.userId,userId,dateFormat.format('yyyy-MM-dd hh:mm:ss')], function(err, result) {
                                        if (err) {
                                            console.log(err);
                                            //回滚
                                            connection.rollback(function() {
                                                console.log('出现错误,回滚!');
                                                //释放资源
                                                connection.release();
                                                res.json({code:config.code.error,message:err,content:''})
                                            });
                                            return;
                                        }
                                        //查询
                                        connection.query($sql.relationshipAddFind, [req.session.user.userId,userId], function(err, result) {
                                            if (err) {
                                                console.log(err);
                                                //回滚
                                                connection.rollback(function() {
                                                    console.log('出现错误,回滚!');
                                                    //释放资源
                                                    connection.release();
                                                    res.json({code:config.code.error,message:err,content:''})
                                                });
                                                return;
                                            }

                                            //增加被发起人信息
                                            connection.query($sql.addMessage, [userId,result[0].id,req.session.user.userName+'发起，是否通过？',0,dateFormat.format('yyyy-MM-dd hh:mm:ss')], function(err, result) {
                                                if (err) {
                                                    console.log(err);
                                                    //回滚
                                                    connection.rollback(function() {
                                                        console.log('出现错误,回滚!');
                                                        //释放资源
                                                        connection.release();
                                                        res.json({code:config.code.error,message:err,content:''})
                                                    });
                                                    return;
                                                }
                                                //提交
                                                connection.commit(function(err) {
                                                    if (err) {
                                                        console.log(err);
                                                        return;
                                                    }
                                                    console.log('成功,提交!');
                                                    //释放资源
                                                    connection.release();
                                                    res.json({code:config.code.success,message:config.message.success,content:result})
                                                });
                                            })
                                        })
                                    })
                                });
                            })
                        }else {
                            res.json({ code: config.code.valNull,'message': '关系已存在',content:result});
                        }
                    });
                }else {
                    connection.release();
                    res.json({ code: config.code.valNull,'message': '用户不存在',content:result});
                }

            });
        });

    },

    /*关系信息明细*/
    relationshipInfo: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);
        //必填参数是否传值
        if(body.id == undefined){
            res.json({ code: config.code.parameterNull,'message': config.message.parameterNull+'id',content:''});
            return;
        }
        var id=body.id || null;
        //必填参数是否为空
        if(id == null){
            res.json({ code: config.code.valNull,'message': config.message.valNull+'id',content:''});
            return;
        }
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.relationshipInfo, [id], function(err, result) {
                connection.release();
                if (err) {
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                res.json({ code: config.code.success,'message': config.message.success,content:result});
            });
        });

    },
    /*转金额*/
    relationshipMoney: function (req, res, next) {
        // 获取前台页面传过来的参数
        var body = new config.reqBody(req);
        //必填参数是否传值
        if(body.id == undefined||body.money == undefined){
            res.json({ code: config.code.parameterNull,'message': config.message.parameterNull+'id money',content:''});
            return;
        }
        var id=body.id || null;
        var money=body.money || null;
        //必填参数是否为空
        if(id == null||money == null){
            res.json({ code: config.code.valNull,'message': config.message.valNull+'id money',content:''});
            return;
        }

        if(config.veriMoney(money)){
            res.json({ code: config.code.valError,'message': '金额非法',content:''});
            return;
        }
        money=parseFloat(money);
        mysql.pool.getConnection(function(err, connection) {
            connection.query($sql.relationshipMoneyFind, [id], function(err, result) {
                if (err) {
                    connection.release();
                    console.log(err);
                    res.json({ code: config.code.error,'message': err,content:''});
                    return;
                }
                if(result.length>0){
                    var payMoney=parseFloat(result[0].payMoney);
                    var collectMoney=parseFloat(result[0].collectMoney);
                    var userId='';          //被转用户ID，用于添加信息通知
                    var relationshipId=result[0].id;  //，用于添加信息通知

                    if(req.session.user.userId==result[0].payUserId){
                        payMoney+=money;
                        userId=result[0].collectUserId;
                    }else if(req.session.user.userId==result[0].collectUserId) {
                        collectMoney+=money;
                        userId=result[0].payUserId;
                    }else {
                        connection.release();
                        res.json({ code: config.code.valError,'message': '用户登录信息错误，请重新登录',content:result});
                    }
                    var resMoney=payMoney-collectMoney;
                    connection.query($sql.relationshipMoney, [payMoney,collectMoney,resMoney,id], function(err, result) {
                        if (err) {
                            connection.release();
                            console.log(err);
                            res.json({ code: config.code.error,'message': err,content:''});
                            return;
                        }
                        connection.query($sql.addMessage, [userId,relationshipId,req.session.user.userName+' 向你转了'+money+'元',1,dateFormat.format('yyyy-MM-dd hh:mm:ss')], function(err, result) {
                            connection.release();
                            if (err) {
                                console.log(err);
                                res.json({ code: config.code.error,'message': err,content:''});
                                return;
                            }
                            res.json({ code: config.code.success,'message': '转帐成功',content:''});
                        });
                    });
                }else {
                    connection.release();
                    res.json({ code: config.code.valNull,'message': '数据不存在',content:result});
                }
            });
        });

    },

};